﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace BillBook.Repository
{
    public class BillBookRepository: IBillBookRepository
    {
        public ISession session;

        public BillBookRepository()
        {
            session = ConfigurationFactory.GetSessionFactory(new[] { "BillBook.Model" }).OpenSession();

        }

        public void Save<T>(T entity)
        {
            session.Persist(entity);
            session.Flush();
        }

        public void Update<T>(T entity)
        {
            session.Merge(entity);
            session.Flush();
        }

        public void Delete<T>(T entity)
        {
            session.Delete(entity);
            session.Flush();
        }

        public T Load<T>(long id)
        {
            return session.Load<T>(id);
        }

        public List<T> ExecuteNamedQuery<T>(string queryName, IDictionary<string, object> paramters)
        {
            IQuery query = session.GetNamedQuery(queryName);
           foreach (KeyValuePair<string, object> paramter in paramters)
           {
               query.SetParameter(paramter.Key, paramter.Value);
           }

            IList list = query.List();
            var ts = new List<T>();
            foreach (var item in list)
            {
                ts.Add((T)item);
            }
            return ts;
       }

        public List<T> ExecuteNamedQueryList<T>(string queryName, IDictionary<string, object> paramters, int startrecordno, int numofrecords)
        {
            IQuery query = session.GetNamedQuery(queryName).SetFirstResult(startrecordno).SetMaxResults(numofrecords);
            foreach (KeyValuePair<string, object> paramter in paramters)
            {
                query.SetParameter(paramter.Key, paramter.Value);
            }

            IList list = query.List();
            var ts = new List<T>();
            foreach (var item in list)
            {
                ts.Add((T)item);
            }
            return ts;
        }

        public object ExecuteScalar<T>(string queryName, IDictionary<string, object> paramters)
        {
            IQuery query = session.GetNamedQuery(queryName);
            if (paramters != null)
                foreach (KeyValuePair<string, object> paramter in paramters)
                {
                    query.SetParameter(paramter.Key, paramter.Value);
                }
            return query.UniqueResult();
        }


        public void Dispose()
        {
            if ((session != null) && (session.IsOpen))
            {
                session.Close();
                session.Dispose();
                session = null;
            }
        }
    }
}